﻿<%@ WebHandler Language="C#" Class="ProductWorkflowDataViewVue3PageHandler" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Data;
using System.Collections;
using System.Collections;
using System.Collections.Generic;
using BusinessRule.DTO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using DatabaseAccess.DBUtility;
using Camstar.WebClient.FormsBuilder.WebForm;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using External.APICalling;

public class ProductWorkflowDataViewVue3PageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private uLMSDispatchIBusiness m_DispatchObj = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    private uLMSStepCheckPointIBusiness m_CheckPointObj = uMESBusinessFactory.instance.GetuLMSStepCheckPointObject();
    private uLMSStepRelevantToSonWFStepIBusiness m_StepRelevanToSonWFStepObj = uMESBusinessFactory.instance.GetuLMSStepRelevantToSonWFStepObject();
    private uLMSStepTimeIBusiness stepTimeBusiness = uMESBusinessFactory.instance.GetuLMSStepTimeObject();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetWorkflowSelect"://获取工艺路线下拉数据（件号下拉组件）
                    GetWorkflowSelectData(context);
                    break;
                case "getProductInfoData"://查询件号信息
                    getProductInfoData(context);
                    break;
                case "getWorkflowInfoData"://查询工艺信息
                    getWorkflowInfoData(context);
                    break;
                case "getWorkflowStepData"://查询工序信息
                    getWorkflowStepData(context);
                    break;
                case "getWorkflowDetailData"://查询工艺明细（检测项、Bom、工装工具、辅材、超越单）
                    getWorkflowDetailData(context);
                    break;
                case "ChangeBomDetailInfo"://BOM属性维护
                    ChangeBomDetailInfo(context);
                    break;
                case "WorkFlowViewPrint"://工艺预览
                    WorkFlowViewPrint(context);
                    break;
                case "GetStepRelevanToSubWFStepData"://工艺关联子工艺工序--查询
                    GetStepRelevanToSubWFStepData(context);
                    break;
                case "GetSonWFOtherWorkflowStepData"://工艺关联子工艺工序--查询其他子工艺工序信息
                    GetSonWFOtherWorkflowStepData(context);
                    break;
                case "SaveStepRelevanToSubWFStepData"://工艺关联子工艺工序--保存
                    SaveStepRelevanToSubWFStepData(context);
                    break;
                case "GetSmallStageData"://部件小阶段--查询
                    GetSmallStageData(context);
                    break;
                case "SaveSmallStageData"://部件小阶段--保存
                    SaveSmallStageData(context);
                    break;
                case "GetProductmateriallistitem"://限制信息维护--查询
                    GetProductmateriallistitem(context);
                    break;
                case "SaveProductmateriallistitem"://限制信息维护--保存
                    SaveProductmateriallistitem(context);
                    break;
                case "getSpecialCourseDataList"://查询特殊过程列表信息
                    getSpecialCourseDataList(context);
                    break;
                case "getSpecialCourseDetailList"://查询特殊过程明细信息
                    getSpecialCourseDetailList(context);
                    break;
                case "GetThreeFixedCardsData"://查询三定卡片数据
                    GetThreeFixedCardsData(context);
                    break;
                case "GetThreeFixedCardDetail"://查询三定卡片明细数据
                    GetThreeFixedCardDetail(context);
                    break;
                case"UpdateWorkflowStatus"://启用工艺版本
                    UpdateWorkflowStatus(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 获取工艺规程下拉数据
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkflowSelectData(HttpContext context)
    {
        string FactoryID = m_UserInfo == null ? context.Request["factoryid"].ToString() : m_UserInfo.FactoryID;
        string FactoryCode = m_UserInfo == null ? context.Request["factorycode"].ToString() : m_UserInfo.FactoryCode;
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "查询完成" };
        string productNames = context.Request["productName"].ToString();
        string workflowName = context.Request["workflowName"].ToString();
        DataTable dtWorkflow = new DataTable();
        if (string.IsNullOrWhiteSpace(productNames))
        {
            dtWorkflow = stepTimeBusiness.GetWorkflowOfNoRelevantToProduct(workflowName, FactoryID);
        }
        else
        {
            bool isThisFactory = bool.Parse(context.Request["isThisFactory"].ToString());
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string productName = productNames.Substring(0, productNames.IndexOf(":"));
            dic.Add("ProductName", productName);
            productNames = productNames.Replace(productName + ":", "");
            int len = productNames.IndexOf("(") == -1 ? productNames.Length : productNames.IndexOf("(");
            string productRev = productNames.Substring(0, len);
            dic.Add("ProductRev", productRev);
            if (isThisFactory)
            {
                dic.Add("FactoryID", FactoryID);
            }
            if (FactoryCode.Equals("603") || FactoryCode.Equals("628")) //add by longb 2023-06-19 试车、装配特殊查询
            {
                dic.Add("ZS", "");
            }
            if(m_UserInfo==null||!m_UserInfo.Roles.Contains("工艺管理员")){
                dic.Add("WorkFlowIsUse", "0");//工艺路线是否有效（1有效；0无效） by duht 2024-8-15
            }
            dtWorkflow = m_CommonObj.GetWorkflowInfoWithOtherAndSubByProductInfo(dic, false, isThisFactory);
        }
        if (dtWorkflow.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "没有工艺";
        }
        result.DBTable = dtWorkflow;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询件号信息
    /// </summary>
    /// <param name="context"></param>
    private void getProductInfoData(HttpContext context)
    {
        var result = new uMESProcessResult();
        var ProductInfo = context.Request["ProductInfo"].ToString();
        var productname = ProductInfo.Split(':')[0];
        var revision = ProductInfo.Split(':')[1].Split('(')[0];
        DataTable dtMaterial = m_CommonObj.GetMaterialByProduct(productname, revision);
        if (dtMaterial.Rows.Count > 0)
        {
            result.Result = true;
            result.DBTable = dtMaterial;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询工艺信息
    /// </summary>
    /// <param name="context"></param>
    private void getWorkflowInfoData(HttpContext context)
    {
        var result = new uMESProcessResult();
        var workflowid = context.Request["workflowid"].ToString();
        DataTable dtProductFamily = m_CommonObj.GetWorkflowPorductFamily(workflowid);
        DataTable dtWorkFlowEmp = m_CommonObj.GetWorkFlowEmpAndFactoryByWorkFlowID(workflowid);
        DataTable AllWkflBom = m_CommonObj.GetBomByWorkflowID(workflowid);
        DataView bom_defaultView = AllWkflBom.DefaultView;//消耗件
        bom_defaultView.RowFilter = String.Format("BILLTYPENAME='BOM'");
        DataTable dt_bom = bom_defaultView.ToTable();
        DataView pm_defaultView = AllWkflBom.DefaultView;//集件
        pm_defaultView.RowFilter = String.Format("BILLTYPENAME='PRODUCTMATERIAL'");
        DataTable dt_MP = pm_defaultView.ToTable();
        var para = new Dictionary<string, string>();
        para.Add("BOMNAME", "");
        para.Add("BOMID", "");
        if (dt_bom.Rows.Count > 0)
        {
            para["BOMNAME"] = dt_bom.Rows[0]["bomname"].ToString();
            para["BOMID"] = dt_bom.Rows[0]["BOMID"].ToString();
        }
        if (dt_MP.Rows.Count > 0)
        {
            para.Add("COLLECTPRODUCT", dt_MP.Rows[0]["bomname"].ToString());
            para.Add("COLLECTPRODUCTID", dt_MP.Rows[0]["BOMID"].ToString());
            if (string.IsNullOrWhiteSpace(para["BOMID"])) { para["BOMID"] = dt_MP.Rows[0]["BOMID"].ToString(); }
        }

        if (dtWorkFlowEmp.Rows.Count > 0)
        {
            result.Result = true;
            result.DBTable = dtWorkFlowEmp;
        }
        if (dtProductFamily.Rows.Count > 0)
        {
            var PRODUCTFAMILYNAME = string.Join(",", dtProductFamily.AsEnumerable().Select(row => row["PRODUCTFAMILYNAME"].ToString()));
            para.Add("PRODUCTFAMILYNAME", PRODUCTFAMILYNAME);
        }
        result.ReturnData = para;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询工序信息
    /// </summary>
    /// <param name="context"></param>
    private void getWorkflowStepData(HttpContext context)
    {
        var result = new uMESProcessResult();
        var workflowid = context.Request["workflowid"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("WorkflowID", workflowid);
        para.Add("userFactoryID", m_UserInfo == null ? context.Request["factoryid"].ToString() : m_UserInfo.FactoryID);
        DataTable wkflStepDt = m_CommonObj.GetWorkFlowSetpsViewDetailByWorkflowID(para);
        var workflowStepIDs = string.Join(",", wkflStepDt.AsEnumerable().Select(row => row["WORKFLOWSTEPID"].ToString()));
        DataTable stepInfodt = m_CommonObj.GetStepinfoDt(workflowStepIDs);
        var StepInfoIDs = string.Join(",", stepInfodt.AsEnumerable().Select(row => row["STEPINFOID"].ToString()));
        var paraData = new Dictionary<string, string>();
        paraData.Add("workflowStepIDs", workflowStepIDs);
        paraData.Add("StepInfoIDs", StepInfoIDs);
        if (!wkflStepDt.Columns.Contains("StepList"))
        {
            wkflStepDt.Columns.Add("StepList", typeof(System.Object));
            wkflStepDt.Columns.Add("existStep", typeof(System.Boolean));
        }
        foreach (DataRow row in wkflStepDt.Rows)
        {
            DataRow[] steprow = stepInfodt.Select("WORKFLOWSTEPID='" + row["WORKFLOWSTEPID"] + "'");
            if (steprow.Length > 0)
            {
                row["StepList"] = steprow.CopyToDataTable();
                row["existStep"] = true;
            }
            else
            {
                row["existStep"] = false;
            }
        }
        result.DBTable = wkflStepDt;
        result.ReturnData = paraData;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询工艺明细（检测项、Bom、工装工具、辅材、超越单）
    /// </summary>
    /// <param name="context"></param>
    private void getWorkflowDetailData(HttpContext context)
    {
        var result = new uMESProcessResult();
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        //BOM
        DataTable BomDt = m_CommonObj.GetBOM(context.Request["BOMID"].ToString());
        if (!BomDt.Columns.Contains("MATERIALTXNLOGIC"))
        {
            BomDt.Columns.Add("REFERENCEDESIGNATOR", typeof(System.Boolean));
            BomDt.Columns.Add("MATERIALTXNLOGIC", typeof(System.Boolean));
        }
        foreach (DataRow row in BomDt.Rows)
        {
            row["REFERENCEDESIGNATOR"] = row["referencedes"].Equals("中间件");
            row["MATERIALTXNLOGIC"] = row["IssueControl"].ToString().Equals("1");
        }
        if (BomDt.Rows.Count > 0 && !string.IsNullOrWhiteSpace(context.Request["workflowstepname"].ToString()))
        {
            DataRow[] selectRow = BomDt.Select("specname='" + context.Request["workflowstepname"].ToString() + "'");
            BomDt = selectRow.Length > 0 ? selectRow.CopyToDataTable() : new DataTable();
        }
        BomDt.TableName = "bom";
        //工装工具
        DataTable workflowsteptool_dt = m_DispatchObj.GetStepToolsInfo(para["workflowStepIDs"], "WorkflowStep");
        DataTable stepInfotool_dt = m_DispatchObj.GetStepToolsInfo(para["StepInfoIDs"], "StepInfo");
        workflowsteptool_dt.Merge(stepInfotool_dt);
        if (workflowsteptool_dt.Rows.Count > 0 && !string.IsNullOrWhiteSpace(context.Request["workflowstepid"].ToString()))
        {
            DataRow[] selectRow = workflowsteptool_dt.Select("workflowstepid='" + context.Request["workflowstepid"].ToString() + "'");
            workflowsteptool_dt = selectRow.Length > 0 ? selectRow.CopyToDataTable() : new DataTable();
        }
        workflowsteptool_dt.TableName = "tool";
        //辅材
        DataTable workflowstepAux = m_DispatchObj.GetAuxToolsInfoByStepID("'" + para["workflowStepIDs"].Replace(",", "','") + "'", "''", true);
        if (workflowstepAux.Rows.Count > 0 && !string.IsNullOrWhiteSpace(context.Request["workflowstepid"].ToString()))
        {
            DataRow[] selectRow = workflowstepAux.Select("workflowstepid='" + context.Request["workflowstepid"].ToString() + "'");
            workflowstepAux = selectRow.Length > 0 ? selectRow.CopyToDataTable() : new DataTable();
        }
        workflowstepAux.TableName = "aux";
        //超越单信息
        DataSet ds_ = m_CommonObj.GetSupPassInfoByWorkflowProcessNO(context.Request["ProcessNO"].ToString());
        DataTable surpassDt = new DataTable();
        if (ds_.Tables.Count > 0)
        {
            surpassDt = ds_.Tables[0].Copy();
        }
        surpassDt.TableName = "surpass";
        //检测项
        var ProductInfo = context.Request["ProductInfo"].ToString();
        var productname = string.IsNullOrWhiteSpace(ProductInfo) ? "" : ProductInfo.Split(':')[0];
        var revision = string.IsNullOrWhiteSpace(ProductInfo) ? "" : ProductInfo.Split(':')[1].Split('(')[0];
        var oQuery = new Dictionary<string, string>();
        oQuery.Add("ProductName", productname);
        oQuery.Add("ProductRev", revision);
        oQuery.Add("WorkflowID", context.Request["workflowid"].ToString());
        oQuery.Add("StepInfoCheckPoint", "StepInfoCheckPoint");
        uMESProcessResult oResult = m_CheckPointObj.GetStepCheckPointList(oQuery);
        DataTable checkpointDt = oResult.DBTable;
        if (checkpointDt.Rows.Count > 0 && !string.IsNullOrWhiteSpace(context.Request["workflowstepid"].ToString()))
        {
            DataRow[] selectRow = checkpointDt.Select("workflowstepid='" + context.Request["workflowstepid"].ToString() + "'");
            checkpointDt = selectRow.Length > 0 ? selectRow.CopyToDataTable() : new DataTable();
        }
        checkpointDt.TableName = "checkpoint";
        DataSet ds = new DataSet();
        ds.Tables.Add(BomDt);
        ds.Tables.Add(workflowsteptool_dt);
        ds.Tables.Add(workflowstepAux);
        ds.Tables.Add(surpassDt);
        ds.Tables.Add(checkpointDt);
        result.DBDataSet = ds;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// BOM属性维护
    /// </summary>
    /// <param name="context"></param>
    private void ChangeBomDetailInfo(HttpContext context)
    {
        DataTable bomDT = JsonConvert.DeserializeObject<DataTable>(context.Request["bom"].ToString());
        var APIUserName = m_UserInfo == null ? context.Request["APIUserName"].ToString() : m_UserInfo.APIUserName.ToString();
        var APIPassword = m_UserInfo == null ? context.Request["APIPassword"].ToString() : m_UserInfo.APIPassword.ToString();
        var DataEntityList = new List<ClientAPIEntity>();
        var subDataEntityList = new List<ClientAPIEntity>();
        var BomName = bomDT.Rows[0]["BOMNAME"].ToString();
        var BomRev = bomDT.Rows[0]["BOMREVISION"].ToString();
        DataEntityList.Add(new ClientAPIEntity("Name", InputTypeEnum.Details, DataTypeEnum.DataField, BomName, ""));
        DataEntityList.Add(new ClientAPIEntity("Revision", InputTypeEnum.Details, DataTypeEnum.DataField, BomRev, ""));
        var api = new External.APICalling.CamstarClientAPI(APIUserName, APIPassword);
        var p_CheckPointEntity = new Dictionary<string, List<ClientAPIEntity>>();
        var i = 0;
        foreach (DataRow uldr in bomDT.Rows)
        {
            subDataEntityList = new List<ClientAPIEntity>();
            subDataEntityList.Add(new ClientAPIEntity("Product", InputTypeEnum.Details, DataTypeEnum.RevisionedObjectField, uldr["productinfo"].ToString().Split(':')[0], uldr["productinfo"].ToString().Split(':')[1]));
            subDataEntityList.Add(new ClientAPIEntity("Spec", InputTypeEnum.Details, DataTypeEnum.RevisionedObjectField, uldr["specname"].ToString(), uldr["SPECREVISION"].ToString()));
            subDataEntityList.Add(new ClientAPIEntity("QtyRequired", InputTypeEnum.Details, DataTypeEnum.DataField, uldr["qtyrequired"].ToString(), ""));
            subDataEntityList.Add(new ClientAPIEntity("IssueControl", InputTypeEnum.Details, DataTypeEnum.DataField, Convert.ToBoolean(uldr["MATERIALTXNLOGIC"]) ? 1 : 5, ""));
            subDataEntityList.Add(new ClientAPIEntity("referencedesignator", InputTypeEnum.Details, DataTypeEnum.DataField, Convert.ToBoolean(uldr["referencedesignator"]) ? "中间件" : "", ""));
            p_CheckPointEntity.Add(i.ToString(), subDataEntityList);
            i += 1;
        }
        string msg = string.Empty;
        var result = new uMESProcessResult();
        result.Result = api.UpdateModelHasSubentityList("BOMMaintDoc", "BOMMaint", BomName, BomRev, "RO", DataEntityList, "MaterialList", p_CheckPointEntity, bomDT.Rows.Count, ref msg);
        result.Message = msg;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 工艺预览
    /// </summary>
    /// <param name="context"></param>
    private void WorkFlowViewPrint(HttpContext context)
    {
        var result = new uMESProcessResult();
        if (string.IsNullOrWhiteSpace(context.Request["WorkFlowID"].ToString()))
        {
            result.Message = "请选择工艺路线信息再进行操作";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        var wfIDAndProID = new Dictionary<string, string>();
        wfIDAndProID.Add("ProductName", context.Request["ProductName"].ToString());
        wfIDAndProID.Add("ProductDesc", context.Request["ProductDesc"].ToString());
        wfIDAndProID.Add("WorkFlowID", context.Request["WorkFlowID"].ToString());
        wfIDAndProID.Add("IsSelf", "1");
        wfIDAndProID.Add("BomID", context.Request["BomID"].ToString());
        context.Session["PrintInfo"] = wfIDAndProID;

        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 工序关联子工艺工序--查询
    /// </summary>
    /// <param name="context"></param>
    private void GetStepRelevanToSubWFStepData(HttpContext context)
    {
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        if (!string.IsNullOrWhiteSpace(para["sonWorkflowID"]))
        {
            DataTable dt = m_StepRelevanToSonWFStepObj.GetStepRelevantToSonWFStepInfo(para);
            DataTable stepIDAndSonWFID_dt = dt.DefaultView.ToTable(true, new string[] { "workflowstepid", "sonworkflowid", "stepandsubwfinfo" });
            var StepIDs = string.Join(",", stepIDAndSonWFID_dt.AsEnumerable().Select(row => row["workflowstepid"].ToString()));
            var list2 = new ArrayList();
            foreach (DataRow dr in stepIDAndSonWFID_dt.Rows)
            {

                var list = new List<Dictionary<string, object>>();
                foreach (DataRow row in dt.Rows)
                {
                    if (dr["workflowstepid"].ToString().Equals(row["workflowstepid"].ToString()))
                    {
                        var data = new Dictionary<string, object>();
                        data.Add("id", row["sonworkflowstepid"]);
                        data.Add("label", row["sonworkflowstepname"]);
                        data.Add("children", new List<string>());
                        list.Add(data);
                    }
                }
                var data2 = new Dictionary<string, object>();
                data2.Add("id", dr["workflowstepid"] + ":@@key");
                data2.Add("label", dr["stepandsubwfinfo"]);
                data2.Add("children", list);
                list2.Add(data2);
            }
            var data3 = new Dictionary<string, object>();
            data3.Add("id", para["workflowID"]);
            data3.Add("label", para["workflowInfo"]);
            data3.Add("children", list2);
            var list3 = new ArrayList();
            list3.Add(data3);
            var sql = @"select wb.workflowname||':'||w.WORKFLOWREVISION || '(' || w.WORKFLOWTYPE || ')' WORKFLOWNAME,w.workflowid from workflow w
                        left join workflowbase wb on wb.workflowbaseid=w.workflowbaseid 
                        where w.productid in (
                        select w.productid from workflow w
                        where w.workflowid='{0}'
                        ) and w.workflowid!='{0}'";
            var SonWFOtherWFDT = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(String.Format(sql, para["sonWorkflowID"]));
            var dic = new Dictionary<string, object>();
            dic.Add("data", list3);
            dic.Add("StepIDs", StepIDs);
            result.ReturnData = dic;
            result.DBTable = SonWFOtherWFDT;
        }
        else
        {
            var data = new Dictionary<string, object>();
            data.Add("id", para["workflowStepID"]);
            data.Add("label", para["workflowStepName"]);
            data.Add("children", new List<string>());
            var list = new List<Dictionary<string, object>>();
            list.Add(data);
            var data2 = new Dictionary<string, object>();
            data2.Add("id", para["workflowID"] + ":@@key");
            data2.Add("label", para["workflowInfo"]);
            data2.Add("children", list);
            var list2 = new ArrayList();
            list2.Add(data2);
            //var data = @"[{'id':" + para["workflowID"] + ",'label':'" + para["workflowInfo"] + "','children':[{'id':'" + para["workflowStepID"] + "','label':'" + para["workflowStepName"] + "'}]}]";
            var SonWFOtherWFDT = m_StepRelevanToSonWFStepObj.GetSonWFOFOtherWF(para["workflowID"]);
            var dic = new Dictionary<string, object>();
            dic.Add("data", list2);
            dic.Add("StepIDs", para["workflowStepID"]);
            result.ReturnData = dic;
            result.DBTable = SonWFOtherWFDT;
        }
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 工序关联子工艺工序--查询其他子工艺工序信息
    /// </summary>
    /// <param name="context"></param>
    private void GetSonWFOtherWorkflowStepData(HttpContext context)
    {
        DataTable subWFStepInfp_dt = m_CommonObj.GetWorkFlowSetpsByWorkflowID(context.Request["workflowid"].ToString());
        if (subWFStepInfp_dt.Columns.Contains("StepID"))
        {
            subWFStepInfp_dt.Columns.Add("StepID");
            subWFStepInfp_dt.Columns.Add("StepInfo");
        }
        var result = new uMESProcessResult();
        result.DBTable = subWFStepInfp_dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 工序关联子工艺工序--保存
    /// </summary>
    /// <param name="context"></param>
    private void SaveStepRelevanToSubWFStepData(HttpContext context)
    {
        var result = new uMESProcessResult();
        DataTable sonStepDT = JsonConvert.DeserializeObject<DataTable>(context.Request["sondt"].ToString());
        var StepIDs = context.Request["StepIDs"].ToString();
        var workflowid = context.Request["workflowid"].ToString();
        var sonWFID = context.Request["sonWFID"].ToString();
        DataTable dts0 = new DataTable();
        dts0.Columns.Add("workflowID");
        dts0.Columns.Add("workflowStepID");
        DataTable dts1 = new DataTable();
        dts1.Columns.Add("workflowID");
        dts1.Columns.Add("workflowStepID");
        dts1.Columns.Add("sonWorkflowID");
        dts1.Columns.Add("sonWorkflowStepID");
        DataRow[] filterRow = sonStepDT.Select("StepID is null");
        if (filterRow.Length > 0)
        {
            result.Message = "请为所有子工艺工序选择对应的主工艺工序";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        foreach (DataRow row in sonStepDT.Rows)
        {
            var dr = dts1.NewRow();
            dr["workflowID"] = workflowid;
            dr["workflowStepID"] = row["StepID"].ToString();
            dr["sonWorkflowID"] = sonWFID;
            dr["sonWorkflowStepID"] = row["WORKFLOWSTEPID"].ToString();
            dts1.Rows.Add(dr);
        }
        DataTable StepIDs_dt = dts1.DefaultView.ToTable(true, "workflowStepID");
        if (StepIDs_dt.Rows.Count != StepIDs.Split(',').Length)
        {
            result.Message = "请确保主工艺所有子工艺工序存在对应的新版子工艺工序";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        foreach (string stepID in StepIDs.Split(','))
        {
            var dr = dts0.NewRow();
            dr["workflowID"] = workflowid;
            dr["workflowStepID"] = stepID;
            dts0.Rows.Add(dr);
        }
        DataSet ds = new DataSet();
        ds.Tables.Add(dts0);
        ds.Tables.Add(dts1);
        result.Result = m_StepRelevanToSonWFStepObj.AddNewStepRelevantToSonWFSTeps(ds);
        result.Message = result.Result ? "提交成功" : "提交失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 部件小阶段--查询
    /// </summary>
    /// <param name="context"></param>
    private void GetSmallStageData(HttpContext context)
    {
        var result = new uMESProcessResult();
        var productID = context.Request["productid"].ToString();
        DataTable dt = m_CommonObj.GetTableInfo("Userattribute", "Parentid", productID);
        DataRow[] drs = dt.Select("UserattributeName='部件小阶段'");
        if (drs.Length > 0)
        {
            result.ReturnData = drs[0]["Attributevalue"].ToString();
        }
        result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 部件小阶段--保存
    /// </summary>
    /// <param name="context"></param>
    private void SaveSmallStageData(HttpContext context)
    {
        DataTable attrList = JsonConvert.DeserializeObject<DataTable>(context.Request["attrList"].ToString());
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var host = new ServerHostInfo();
        host.UserName = m_UserInfo == null ? context.Request["APIUserName"].ToString() : m_UserInfo.APIUserName;
        host.Password = m_UserInfo == null ? context.Request["APIPassword"].ToString() : m_UserInfo.APIPassword;
        var api = new CamstarClientAPI(host.UserName.ToString(), host.Password.ToString());
        var dataList = new List<ClientAPIEntity>();
        var dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Name";
        dataEntity.ClientDataValue = para["productname"];
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Revision";
        dataEntity.ClientDataValue = para["productrev"];
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataList.Add(dataEntity);
        var m_ChildList = new Dictionary<string, List<ClientAPIEntity>>();
        var childList = new List<ClientAPIEntity>();
        var index = -1;
        foreach (DataRow row in attrList.Rows)
        {
            if (row["Userattributename"].Equals("部件小阶段"))
            {
                continue;
            }
            addAttribute(ref childList, dataEntity, row["Userattributename"].ToString(), row["AttributeValue"].ToString());
            index += 1;
            m_ChildList.Add(index.ToString(), childList);
        }

        if (!string.IsNullOrWhiteSpace(para["attributevalue"]))
        {
            addAttribute(ref childList, dataEntity, "部件小阶段", para["attributevalue"].ToString());
            index += 1;
            m_ChildList.Add(index.ToString(), childList);
        }

        var Message = string.Empty;
        var result = new uMESProcessResult();
        result.Result = api.UpdateModelHasSubentityList("ProductMaintDoc", "ProductMaint", para["productname"].ToString(), para["productrev"].ToString(), "RO", dataList, "Attributes", m_ChildList, attrList.Rows.Count, ref Message);
        result.Message = Message;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void addAttribute(ref List<ClientAPIEntity> childList, ClientAPIEntity dataEntity, string name, string value)
    {
        childList = new List<ClientAPIEntity>();
        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Name";
        dataEntity.ClientDataValue = name;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        childList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "AttributeValue";
        dataEntity.ClientDataValue = value;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        childList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "IsExpression";
        dataEntity.ClientDataValue = "false";
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        childList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "DataType";
        dataEntity.ClientDataValue = "4";
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        childList.Add(dataEntity);
    }
    /// <summary>
    /// 限制信息维护--查询
    /// </summary>
    /// <param name="context"></param>
    private void GetProductmateriallistitem(HttpContext context)
    {
        var BomID = context.Request["BomID"].ToString();
        var strSql = @"SELECT pm.bomid,pm.productmateriallistitemid,pm.yjwjh,pm.zynr,pm.xzsy,DECODE(pm.print_status,1,1,0) print_status,
                pb.productname,p.productid,sb.specname,s.specno,ST.SPECTYPENAME,pb.productname||':'||p.productrevision productinfo,s.specrevision,
                pm.materialtxnlogic IssueControl,pm.referencedesignator referencedes,pm.qtyrequired,pm.qty2required,p.productrevision,p.description pdesc,
                B.NOTES,bb.bomname || ':' || b.bomrevision bomname,PM.STEPINFOID,SIOB.STEPINFONAME,PM.BIGSMALLPART,sio.description stepinfodesc,pm.productmateriallistitemname,b.bomrevision
                FROM productmateriallistitem pm
                LEFT JOIN productbase pb1 ON pb1.productbaseid=pm.productbaseid
                LEFT JOIN product p ON p.productid=NVL(pb1.revofrcdid,pm.productid) 
                LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid 
                LEFT JOIN specbase sb1 ON sb1.specbaseid=pm.specbaseid
                LEFT JOIN spec s ON s.specid=NVL(sb1.revofrcdid,pm.specid) 
                LEFT JOIN specbase sb ON sb.specbaseid=s.specbaseid 
                LEFT JOIN BOM B ON B.BOMID = PM.BOMID
                LEFT JOIN BOMBASE BB ON BB.BOMBASEID = B.BOMBASEID
                LEFT JOIN STEPINFO SIO ON SIO.STEPINFOID = PM.STEPINFOID
                LEFT JOIN STEPINFOBASE SIOB ON SIOB.STEPINFOBASEID = SIO.STEPINFOBASEID
                LEFT JOIN SPECTYPE ST ON ST.SPECTYPEID = SIO.SPECTYPEID 
                WHERE pm.bomid='{0}'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(strSql, BomID));
        var result = new uMESProcessResult();
        result.DBTable = dt;
        result.Result = true; //dt.Rows.Count > 0;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 限制信息维护--保存
    /// </summary>
    /// <param name="context"></param>
    private void SaveProductmateriallistitem(HttpContext context)
    {
        var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        string strSql = String.Format("UPDATE productmateriallistitem pm SET pm.yjwjh = '{0}',pm.zynr = '{1}',pm.xzsy = '{2}',pm.print_status = '{3}' WHERE pm.productmateriallistitemid = '{4}'",
            data["YJWJH"], data["ZYNR"], data["XZSY"], data["PRINT_STATUS"].ToString(), data["PRODUCTMATERIALLISTITEMID"]);
        var result = new uMESProcessResult();
        result.Result = DatabaseHelper.ExecuteSql(strSql) > 0;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询特殊过程列表
    /// </summary>
    /// <param name="context"></param>
    private void getSpecialCourseDataList(HttpContext context)
    {
        var workflowids = context.Request["workflowids"].ToString();
        //        var sql = @"select distinct * from (select wb.workflowname||':'||w.workflowrevision workflowinfo ,ws.workflowstepname,nvl(sc.specialcoursespecreportno,sr.specialcoursespecreportno) specialcoursespecreportno,to_char(sm.createdate,'yyyy-MM-dd hh24:mi:ss') createdate
        //        from specialcoursespecmapp sm 
        //        left join specialcoursespecreport sr on sr.specialcoursespecreportid =sm.specialcoursespecreportid
        //        left join workflow w on w.workflowid =sm.workflowid 
        //        left join workflowbase wb on wb.workflowbaseid =w.workflowbaseid 
        //        left join workflowstep ws on ws.workflowstepid =sm.workflowstepid
        //        left join ( select sk.specialcoursespecreportno,s.code from specialcoursespeccontent s 
        //               inner join specialcoursespecreportbank sk on sk.specialcoursespecreportbankid =s.specialcoursespecreportbankid) sc on INSTR(sr.specialcoursespecreportno,sc.code)>0
        //        where sr.indate is null and sm.workflowid in ('{0}')
        //        union all 
        //        select wb.workflowname||':'||w.workflowrevision workflowinfo ,ws.workflowstepname,sr.specialcoursespecreportno,to_char(sm.createdate,'yyyy-MM-dd hh24:mi:ss') createdate
        //        from specialcoursespecmapp sm 
        //        left join specialcoursespecreport sr on sr.specialcoursespecreportid =sm.specialcoursespecreportid
        //        left join workflow w on w.workflowid =sm.workflowid 
        //        left join workflowbase wb on wb.workflowbaseid =w.workflowbaseid 
        //        left join workflowstep ws on ws.workflowstepid =sm.workflowstepid
        //        where sr.indate is not null and sm.workflowid in ('{0}')
        //        )";
        var sql = @"select wb.workflowname||':'||w.workflowrevision workflowinfo ,ws.workflowstepname,sr.specialcoursespecreportno,to_char(sm.createdate,'yyyy-MM-dd hh24:mi:ss') createdate
        from specialcoursespecmapp sm 
        left join specialcoursespecreport sr on sr.specialcoursespecreportid =sm.specialcoursespecreportid
        left join workflow w on w.workflowid =sm.workflowid 
        left join workflowbase wb on wb.workflowbaseid =w.workflowbaseid 
        left join workflowstep ws on ws.workflowstepid =sm.workflowstepid
        where sm.workflowid in ('{0}')";
        var result = new uMESProcessResult();
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, workflowids.Replace(",", "','")));
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询特殊过程明细信息
    /// </summary>
    /// <param name="context"></param>
    private void getSpecialCourseDetailList(HttpContext context)
    {
        var specialcoursespecreportno = context.Request["specialcoursespecreportno"].ToString();
        //        var sql = @"select sr.specialcoursespecreportno,sr.indate,sr.employeenames,sr.resourcenames from specialcoursespecreport sr where sr.specialcoursespecreportno in('{0}')
        //        union all 
        //        select sc.code specialcoursespecreportno,add_months(sb.indate,regexp_substr(sb.period , '\d+')*12) indate,sc.employeenames ,sc.resourcenames 
        //        from specialcoursespecreportbank sb 
        //        left join specialcoursespeccontent sc on sc.specialcoursespecreportbankid =sb.specialcoursespecreportbankid
        //        where sb.specialcoursespecreportno in('{0}')";
        string sql = @"select sc.code specialcoursespecreportno,to_char(add_months(sb.indate,regexp_substr(sb.period , '\d+')*12),'yyyy-MM-dd hh24:mi:ss') indate,sc.employeenames ,sc.resourcenames 
        from specialcoursespecreportbank sb 
        left join specialcoursespeccontent sc on sc.specialcoursespecreportbankid =sb.specialcoursespecreportbankid
        WHERE {0}";
        string sqlWhere = string.Empty;
        string[] nos = specialcoursespecreportno.Split(',');
        DataTable dtRes = new DataTable();
        for (int i = 0; i < nos.Length; i++)
        {
            sqlWhere = string.Format(" sc.code LIKE '{0}%'", nos[i]);
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, sqlWhere));
            if (dt.Rows.Count == 0)
            {
                sqlWhere = string.Format(" sb.specialcoursespecreportno LIKE '{0}%'", nos[i]);
                dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, sqlWhere));
            }
            dtRes.Merge(dt);
        }
        var result = new uMESProcessResult();
        result.DBTable = dtRes;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void GetThreeFixedCardsData(HttpContext context)
    {
        var sql = @"select * from threefixedcards t where t.productname ='{0}'
                and t.workflowname  in (select wb.workflowname from workflowbase wb left join workflow w on w.workflowbaseid=wb.workflowbaseid where w.workflowid in('{1}'))";
        var dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, context.Request["productname"], context.Request["workflowids"].Replace(",", "','")));
        foreach (DataColumn column in dt.Columns)
        {
            column.ColumnName = column.ColumnName.ToLower();
        }
        var result = new uMESProcessResult();
        result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void GetThreeFixedCardDetail(HttpContext context)
    {
        var id = context.Request["id"].ToString();
        var sql = @"select * from threefixedcarddetail td where td.parentid ='{0}'";
        var dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, id));
        foreach (DataColumn column in dt.Columns)
        {
            column.ColumnName = column.ColumnName.ToLower();
        }
        var result = new uMESProcessResult();
        result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    private void UpdateWorkflowStatus(HttpContext context)
    {
        var result = new uMESProcessResult();
        result.Result = DatabaseHelper.ExecuteSql(string.Format(@"update workflow set isuse=0 where workflowid='{0}'", context.Request["workflowid"].ToString())) > 0;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

}